<template>
  <div class="goods-add">
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <!-- 提示框 -->
      <el-alert
        title="消息提示的文案"
        type="info"
        center
        show-icon
        :closable="false"></el-alert>
      <el-steps
        :space="200"
        :active="activeIndex - 0"
        finish-status="success"
        align-center>
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <el-form
        :label-position="'top'"
        :rules="addGoodsFormRules"
        :model="addGoodForm"
        ref="addGoodRef">
        <el-tabs
          :tab-position="'left'"
          @tab-click="tabClick"
          :before-leave="beforeTabLeave"
          v-model="activeIndex">
          <el-tab-pane label="基本信息" name="0">
            <!-- 第一页 -->
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="addGoodForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input v-model="addGoodForm.goods_price"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input v-model="addGoodForm.goods_weight"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input v-model="addGoodForm.goods_number"></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="goods_cat">
              <el-cascader
                v-model="addGoodForm.goods_cat"
                :options="cateList"
                :props="cascader.props"
                @change="cateChange"></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name="1">
            <!-- 第二页 -->
            <el-form-item
              v-for="(value1, index1) in manyParamsList"
              :key="value1.attr_id"
              :label="value1.attr_name">
              <el-checkbox-group
                v-model="addGoodForm.goods_vals[index1].attr_vals">
                <el-checkbox
                  border
                  v-for="(value2, index2) in value1.attr_vals"
                  :key="value1.attr_id + index2"
                  :label="value2"></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2">
            <!-- 第三页 -->
            <el-form-item
              v-for="(value1, index1) in onlyParamsList"
              :key="value1.attr_id + index1"
              :label="value1.attr_name">
              <el-input
                v-model="value1.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <!-- 第四页 -->
            <el-upload
              :action="uploadInfo.uploadURL"
              :on-success="handleFileSuccess"
              :on-remove="handleFilesRemove"
              :on-preview="handlePreview"
              list-type="picture"
              :headers="uploadHeader">
              <el-button type="primary">点击上传</el-button>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <!-- 第五页 -->
            <quill-editor
              v-model="addGoodForm.goods_introduce"></quill-editor>
              <el-button
                type="primary"
                @click="submitAddGood">确认添加</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>
    <!-- 图片预览 -->
    <el-dialog
      :visible.sync="previewDialogVisible"
      title="图片预览">
      <img :src="previewImg" alt="" class="previewImg">
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'GoodsAdd',
  data () {
    return {
      // 步骤条参数
      activeIndex: 0,
      // 分类数据
      cateList: [],
      // 获取动态参数
      manyParamsList: [],
      // 获取静态属性
      onlyParamsList: [],
      // 添加商品的参数
      addGoodForm: {
        // 第一页
        goods_name: '1',
        goods_price: '1',
        goods_weight: '1',
        goods_number: '1',
        goods_cat: '',
        // 存放动态参数
        goods_vals: [],
        goods_introduce: '',
        pics: []
      },
      // form规则
      addGoodsFormRules: {
        goods_name: [
          { required: true, message: '请输入商品名称', trigger: 'blur' }
        ],
        goods_price: [
          { required: true, message: '请输入商品价格', trigger: 'blur' }
        ],
        goods_weight: [
          { required: true, message: '请输入商品重量', trigger: 'blur' }
        ],
        goods_number: [
          { required: true, message: '请输入商品数量', trigger: 'blur' }
        ],
        goods_cat: [
          { required: true, message: '请选择商品分类', trigger: 'blur' }
        ]
      },
      // 级联表
      cascader: {
        // 获取第三值的值
        value: '',
        // 配置规制
        props: {
          value: 'cat_id',
          label: 'cat_name',
          children: 'children'
        }
      },
      // 上传图片的信息
      uploadInfo: {
        uploadURL: 'http://120.79.70.168:8201/api/private/v1/upload',
        fileList: []
      },
      baseUrl: 'http://120.79.70.168:8201/',
      previewUrl: '',
      previewDialogVisible: false,
      // 完成个个表单的阶段
      formPhases: []
    }
  },
  created () {
    this.getCateList()
    // this.getParamsList()
  },
  computed: {
    uploadHeader () {
      return { Authorization: window.sessionStorage.getItem('token') }
    },
    previewImg () {
      return this.baseUrl + this.previewUrl
    }
  },
  methods: {
    // 1. 获取分类数据渲染级联表
    async getCateList () {
      const { data: res } = await this.$http.get('/categories', {
        params: {
          type: '3'
        }
      })
      if (res.meta.status !== 200) {
        return this.$message.error('获取商品分类数据失败')
      }
      // 获取成功
      this.cateList = res.data
    },
    // 2. 获取参数列表
    async getParamsList (type = 'many') {
      const { data: res } = await this.$http.get(`/categories/${this.cascader.value}/attributes`, {
        params: {
          sel: type
        }
      })
      if (res.meta.status !== 200) {
        return this.$message.error('获取参数列表失败')
      }
      // 获取成功
      if (type === 'many') {
        res.data.forEach(value => {
          value.attr_vals = value.attr_vals.split(',')
        })
        this.manyParamsList = res.data
        // console.log(this.manyParamsList)
        this.addGoodForm.goods_vals = this.$deepClone(this.manyParamsList)
      } else if (type === 'only') {
        this.onlyParamsList = res.data
      }
    },
    // 3. 级联表变化
    cateChange () {
      if (this.addGoodForm.goods_cat.length === 3) {
        this.cascader.value = this.addGoodForm.goods_cat[2]
      }
    },
    // 4. 点击tabs
    tabClick (a) {
      if (this.activeIndex === '1') {
        console.log('获取动态参数')
        this.getParamsList('many')
      } else if (this.activeIndex === '2') {
        console.log('获取静态属性')
        this.getParamsList('only')
      }
      // console.log('tabClick被点击了')
    },
    // 5. tab拦截函数
    beforeTabLeave (newIndex, oldIndex) {
      // 把string转换为number
      if (oldIndex) {
        oldIndex = parseInt(oldIndex)
      }
      newIndex = parseInt(newIndex)
      // 添加按顺序判断
      if (newIndex === this.formPhases.length || this.formPhases[newIndex]) {
        // 没有选择分类进行拦截
        if (!this.cascader.value && (oldIndex === 0)) {
          // 拦截
          this.$message.error('请先选择商品分类')
          return false
        }
        // 按顺序执行则数组对应当前的newIndex赋予一个true
        this.formPhases[newIndex] = true
      } else {
        // 不符合顺序进行或者没有通行证(formPhases阶段记录是否有当前newIndex)则拦截
        this.$message.error('请按顺序填写表单')
        return false
      }
    },
    // 6. 上传图片
    handleFileSuccess (response) {
      if (response.meta.status !== 200) {
        return this.$message.error('上传失败')
      }
      const picInfo = { pic: response.data.tmp_path }
      this.addGoodForm.pics.push(picInfo)
      console.log(this.addGoodForm.pics)
    },
    // 7. 移除图片
    handleFilesRemove (file, fileList) {
      const index = this.addGoodForm.pics.findIndex(item => item.pic === file.response.data.tmp_path)
      this.addGoodForm.pics.splice(index, 1)
      console.log(this.addGoodForm.pics)
    },
    // 8. 预览图片
    handlePreview (file) {
      console.log(file)
      this.previewUrl = file.response.data.tmp_path
      this.previewDialogVisible = true
    },
    // 9. 确认添加商品
    submitAddGood () {
      this.$refs.addGoodRef.validate(async valid => {
        if (!valid) return this.$message.error('请核对商品内容')
        const form = this.$deepClone(this.addGoodForm)
        // 变为string
        form.goods_cat = form.goods_cat.join()
        // 存放参数
        form.attrs = []
        // 动态参数
        form.goods_vals.forEach(item => {
          const newObj = { attr_id: item.attr_id, attr_value: item.attr_vals.join() }
          form.attrs.push(newObj)
        })
        // 静态参数
        this.onlyParamsList.forEach(item => {
          const newObj = { attr_id: item.attr_id, attr_value: item.attr_vals }
          form.attrs.push(newObj)
        })
        console.log(form)
        const { data: res } = await this.$http.post('/goods', form)
        if (res.meta.status !== 201) {
          return this.$message.error('添加商品失败')
        }
        // 添加成功
        this.$message.success('添加商品成功')
        // 重定向
        this.$router.push('/goods')
      })
    }
  }
}
</script>

<style scoped lang="less">
.goods-add {
  .el-breadcrumb {
    font-size: 12px;
  }
  .el-card {
    margin-top: 15px;
    .el-steps {
      margin-top: 15px;
    }
    .el-tabs {
      margin-top: 10px;
    }
  }
}
.previewImg {
  width: 100%;
}
</style>
<style lang="less">
.goods-add {
  .el-step__title {
    font-size: 12px !important;
  }
  .el-checkbox {
    margin: 10px 20px !important;
  }
  .ql-editor {
    min-height: 300px;
  }
}
</style>
